package com.pcbly.web.components.license.validator;

import java.security.KeyFactory;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pcbly.web.components.license.License;
import com.pcbly.web.components.license.LicenseException;

public class CheckSignatureValidator implements Validator {
	private static final Log logger = LogFactory
			.getLog(CheckSignatureValidator.class);

	public CheckSignatureValidator() {
	}

	public void validate(License license) throws LicenseException {
		try {
			String publicKey = "308201b73082012c06072a8648ce3804013082011f02818100fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c70215009760508f15230bccb292b982a2eb840bf0581cf502818100f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d0782675159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243bcca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a038184000281800af088055b9304337d285bd946e095465b6d16472e8fc4c29ab735d46fed6140236a3227a2afce0ec54d0002cb95a4988a3e545b1c58c030515c24ecc3de6763fca3f09e05ca568a594d370b879a338043ee3c5a6fe26e95c2b749ce4a8150cd61dd0459e6d5d0862a1ca857c8efc55c73ef3e883ca89eb8358b7147d06d854a";
			byte pub[] = Hex.decodeHex(publicKey.toCharArray());
			X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pub);
			KeyFactory keyFactory = KeyFactory.getInstance("DSA");
			java.security.PublicKey pubKey = keyFactory
					.generatePublic(pubKeySpec);
			Signature sig = Signature.getInstance("DSA");
			sig.initVerify(pubKey);
			byte decoded[] = Hex
					.decodeHex(license.getLicenseData().getSignature().toCharArray());
			logger.info((new StringBuilder()).append(
					"Validating license. License fingerprint: ").append(
							license.getLicenseData().getSignature()).toString());
			sig.update(license.getFingerprint());
			boolean verified = sig.verify(decoded);
			if (!verified)
				throw new LicenseException("License signature is invalid.");
		} catch (Exception e) {
			logger.error( e.getMessage(), e);
			throw new LicenseException(e);
		}
	}

}
